import 'package:flutter/cupertino.dart';
import 'package:power_house/config.dart';
import 'package:power_house/entity/user_entity.dart';
import 'package:power_house/util/common_toast.dart';
import 'package:power_house/util/dio_http.dart';
import 'package:power_house/util/store.dart';
import 'package:power_house/util/string_util.dart';
import 'package:scoped_model/scoped_model.dart';

class AuthModel extends Model {
  String _token = '';
  UserEntity? _userEntity;

  String get token => _token;

  bool get isLogin => _token.isNotEmpty;

  UserEntity? get user => _userEntity;

  void initApp(BuildContext context) async {
    Store store = await Store.getInstance();
    String token = await store.getString(StoreKeyList.loginToken);
    if (!stringIsNullOrEmpty(token)) {
      //token不为空
      if (context.mounted) {
        //异步调用context需要先判断Widget此上下文是否与当前挂载在小部件树中
        login(token, context);
      }
    }
  }

  void login(String token, BuildContext context) {
    _token = token;
    notifyListeners();
    _getUserEntity(context);
  }

  void logout() {
    _token = '';
    _userEntity = null;
    notifyListeners();
  }

  _getUserEntity(BuildContext context) async {
    const url = '${Config.baseUrl}/userinfo';
    var response = await DioHttp.of(context).get(url);
    var responseMap = response.data;
    if (responseMap == null) {
      CommonToast.showToast('获取用户信息失败');
      return;
    }
    _userEntity = UserEntity.fromJson(responseMap['data']['user']);
    notifyListeners();
  }
}
